    'use strict'

    ###*
     # @ngdoc service
     # @name iInvoiceApp.authFactory
     # @description
     # # authFactory
     # Factory in the iInvoiceApp.
    ###
    app = angular.module 'app'
  
    app.factory 'authFactory', [
      '$http'
      '$q'
      'localStorageService'
      ($http, $q, localStorageService) ->
        serviceBase = 'http://ngauthenticationapi.azurewebsites.net/'

        authServiceFactory = {}

        _authentication = 
          isAuth: false
          userName: ''

        _saveRegistration = (registration) ->
          _logOut()

          $http.post(serviceBase + 'api/account/register', registration).then (response) ->
            response

        _login = (loginData) ->
          data = 'grant_type=password&username=' + loginData.userName + '&password=' + loginData.password
          deferred = $q.defer()
          $http.post(serviceBase + 'token', data, headers: 'Content-Type': 'application/x-www-form-urlencoded').success((response) ->
            localStorageService.set 'authorizationData',
              token: response.access_token
              userName: loginData.userName
            _authentication.isAuth = true
            _authentication.userName = loginData.userName
            deferred.resolve response
            return
          ).error (err, status) ->
            _logOut()
            deferred.reject err
            return
          deferred.promise

        _logOut = ->
          localStorageService.remove 'authorizationData'
          _authentication.isAuth = false
          _authentication.userName = ''
          return

        _fillAuthData = ->
          authData = localStorageService.get('authorizationData')
          if authData
            _authentication.isAuth = true
            _authentication.userName = authData.userName
          return   

        authServiceFactory.saveRegistration = _saveRegistration
        authServiceFactory.login = _login
        authServiceFactory.logOut = _logOut
        authServiceFactory.fillAuthData = _fillAuthData
        authServiceFactory.authentication = _authentication
        authServiceFactory
    ]
